//
//  ZFFaceInfoViewController.m
//  HappilyLoan
//
//  Created by zainishenbian on 2017/3/24.
//  Copyright © 2017年 zongqingxiangqian. All rights reserved.
//

#import "ZFFaceInfoViewController.h"
#import "ZFDQKViewController.h"
#import "ZFHeader.h"
#import "ReviewResultsViewController.h"
@interface ZFFaceInfoViewController ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate,UIAlertViewDelegate>
{
    NSString *startTime;
    
    UIButton *selectedButton;
    
    NSArray *picButtonArray;
    
    NSDictionary *dictData;
}
@property (nonatomic,strong) UIAlertController *sheetV;
@property (nonatomic,strong) UIImagePickerController *imagePicker;
@property (nonatomic,strong) AnimatingView *animation;
@property (nonatomic,strong) AlertBoxView *alertV;

@end

@implementation ZFFaceInfoViewController
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [MobClick beginLogPageView:@"faceInfo"];
    self.navigationController.navigationBarHidden = NO;
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [MobClick endLogPageView:@"faceInfo"];
}
- (void)viewDidLoad {
    [super viewDidLoad];

    self.navigationItem.title = @"人脸识别";
    
    [self initData];
}
- (void)initData
{
    startTime = [ZFPulicAPI getCurrentTimestamp];
    
    _animation = [[AnimatingView alloc] init];
    
    _alertV = [[AlertBoxView alloc] init];
    [self.view addSubview:_alertV];

    picButtonArray = @[_faceButton,_IDFrontButton,_IDReverseButton];
    
    _sheetV = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    [_sheetV addAction:[UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        _imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;

        //判断是否支持相机
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            
            [self presentViewController:_imagePicker animated:YES completion:nil];

        }
    }]];
    [_sheetV addAction:[UIAlertAction actionWithTitle:@"从相册选取" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        _imagePicker.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
        [self presentViewController:_imagePicker animated:YES completion:nil];
    }]];
    [_sheetV addAction: [UIAlertAction actionWithTitle: @"取消" style: UIAlertActionStyleCancel handler:nil]];
    
    _imagePicker = [[UIImagePickerController alloc] init];
    _imagePicker.delegate = self;
    _imagePicker.allowsEditing = YES;
}
#pragma mark ———— UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
    if (picker.sourceType == UIImagePickerControllerSourceTypeCamera)
    {
        UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);
    }

    [selectedButton setImage:nil forState:UIControlStateNormal];
    [selectedButton setBackgroundImage:image forState:UIControlStateNormal];
    [self saveImage:image withFilePath:[NSString stringWithFormat:@"%ld.jpg",(long)selectedButton.tag]];
    
    [picker dismissViewControllerAnimated:YES completion:nil];
}
//将头像保存到本地
- (void)saveImage:(UIImage *)tempImage withFilePath:(NSString *)fileParh
{
    //    NSData *imageData = UIImagePNGRepresentation(tempImage);
    NSData *imageData = UIImageJPEGRepresentation(tempImage, 0.3);
    
    NSString *filePath = [self filePathName:fileParh];
    
    [imageData writeToFile:filePath atomically:YES];
}
//获取头像路径
- (NSString *)filePathName:(NSString *)path
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString* documentsDirectory = [[paths objectAtIndex:0] stringByAppendingPathComponent:[NSString stringWithFormat:@"%@",path]];
    return documentsDirectory;
}

//从本地获取图片
- (NSArray *)getPicData
{
    NSMutableArray *imgDataArray = [[NSMutableArray alloc] init];
    
    for (int i = 0; i < 3 ; i ++)
    {
        if ([[NSFileManager defaultManager] fileExistsAtPath:[self filePathName:[NSString stringWithFormat:@"%d.jpg",i+1]]])
        {
            NSData *imageData = [NSData dataWithContentsOfFile:[self filePathName:[NSString stringWithFormat:@"%d.jpg",i+1]]];
            [imgDataArray addObject:imageData];
        }
    }
    return imgDataArray;
}

#pragma mark ———— button的点击事件
- (IBAction)uploadPic:(id)sender {
    
    UIButton *button = (UIButton *)sender;
    selectedButton = button;
    [self presentViewController:_sheetV animated: YES completion: nil];
}
//提交验证
- (IBAction)submitVerify:(id)sender {
    
//    if ([self judgeSumbitInfo]) {
//        
//        ZFUserIDVerifyInfomodal *modal = [ZFUserIDVerifyInfomodal new];
//        modal.startTime = startTime;
//        modal.picArray = [self getPicData];
//        
        [_animation startTheSmallAnimation];
//        [ZFApplyInfoHttpRequest requestSubmitUserIDVerifyInfo:modal sucessBlock:^(NSDictionary *dict) {
            [self performSelector:@selector(stopAni) withObject:self afterDelay:3];
//            dictData = dict;
//
//        } failureBlock:^(NSInteger failSign) {
//            
//            [_animation stopTheSmallAnimation];
//            [_alertV appearAndDisappearAlertWithString:@"网络连接失败"];
//        }];
//    }
}
//- (BOOL)judgeSumbitInfo
//{
//    for (UIButton *button in picButtonArray) {
//        
//        if (!button.currentBackgroundImage) {
//            
//            [_alertV appearAndDisappearAlertWithString:@"信息不完善"];
//            return NO;
//        }
//    }
//    
//    return YES;
//}
//停止动画
- (void)stopAni
{
    [_animation stopTheSmallAnimation];
    ReviewResultsViewController *RRVC = [[ReviewResultsViewController alloc] init];
    RRVC.url = @"https://www.baidu.com";
    [self.navigationController pushViewController:RRVC animated:YES];
//    if ([dictData[@"is_alert"] integerValue] == 1) {
//        
//        [_alertV appearAndDisappearAlertWithString:dictData[@"msg"]];
//    }
//    
//    if ([dictData[@"code"] integerValue] == 1) {
//
//        if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"phone"] isEqualToString:@"18725835901"]) {
//            
//            UIAlertView *alertV = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"您的认证资料提交成功，我司审核需要3-7天，请您耐心等待！" delegate:self cancelButtonTitle:nil otherButtonTitles:@"我知道了", nil];
//            alertV.tag = 1;
//            [alertV show];
//            
//        }
//        else
//        {
//            UIAlertView *alertV = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"sorry,您的认证信息审核失败，我们将推荐更多优质产品给您！" delegate:self cancelButtonTitle:nil otherButtonTitles:@"立即查看", nil];
//            alertV.tag = 2;
//            [alertV show];
//        }
//    }
    
}
#pragma mark ———— alertView delegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.tag == 1) {
       
        [self.navigationController popToRootViewControllerAnimated:YES];
        AppDelegate *delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
        if (delegate.isFirstEnterApp == YES) {
            
            delegate.isFirstEnterApp = NO;
        }
    }
    if (alertView.tag == 2) {
        
        [ZFHomeHttpRequest requestDQKListInfoApplyamt:@"0" loanTerm:@"0" Complete:^(NSDictionary *dict) {

            if ([dict[@"code"] integerValue] == 1) {

                ZFDQKViewController *DQKVC = [ZFDQKViewController new];
                DQKVC.DQKUrl = dict[@"data"][@"configValue"];
                DQKVC.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:DQKVC animated:YES];
            }
        } failureBlock:^(NSInteger failSign) {
            [_alertV appearAndDisappearAlertWithString:@"网络连接失败"];
        }];

    }

}
#pragma mark ———— 返回
- (BOOL)navigationShouldPopOnBackButton
{
    AppDelegate *delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    [self.navigationController popToRootViewControllerAnimated:YES];
    if (delegate.isFirstEnterApp == YES) {
        
        delegate.isFirstEnterApp = NO;
        return NO;
    }
    return NO;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
